package com.ruoyi.feike.controller;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.exception.BaseException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.AsposeUtil;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.feike.domain.DealerInformation;
import com.ruoyi.feike.domain.Grade;
import com.ruoyi.feike.domain.HAml;
import com.ruoyi.feike.domain.HTempContract;
import com.ruoyi.feike.mapper.ContractRecordMapper;
import com.ruoyi.feike.mapper.DealerInformationMapper;
import com.ruoyi.feike.mapper.HAmlMapper;
import com.ruoyi.feike.mapper.HTempContractMapper;
import com.ruoyi.feike.service.IGradeService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.task.Task;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.*;

import static org.aspectj.weaver.tools.cache.SimpleCacheFactory.path;

@RestController
public class ChangTaskController  {

    private static ApplicationContext context = null;

    @Autowired
    private RuntimeService runtimeService;

    @Resource
    private TaskService taskService;


    @GetMapping("/changTask")
    public void changTask(@RequestBody Map<String, Object> map) throws Exception {
        System.out.println("开始");
        System.out.println("接受参数:"+map);
        if(map.get("ids")!=null && map.get("userName")!=null){
            String userName = map.get("userName").toString();
            List<String> ids = (List<String>) map.get("ids");
            try{
                for (String id : ids) {
                    org.activiti.engine.runtime.ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceBusinessKey(id).singleResult();
                    List<org.activiti.engine.task.Task> listTaskXs = taskService.createTaskQuery()
                            .processInstanceId(processInstance.getProcessInstanceId())
                            .list();

                    if(listTaskXs.size()>0){
                        for (Task listTaskX : listTaskXs) {
                            taskService.unclaim(listTaskX.getId());
                            taskService.claim(listTaskX.getId(), userName);
                            System.out.println("任务编号:"+id+"成功派给用户"+userName);
                        }
                    }else{
                        System.out.println("没有查询到任务编号:"+id);
                    }
                }
            }catch (Exception e){
                e.printStackTrace();
            }

        }
        System.out.println("结束");
    }


    @Autowired
    private HTempContractMapper contractRecordMapper;

    @GetMapping("/changPdf")
    public void changPdf(@RequestBody Map<String, Object> map) throws Exception {
        System.out.println("开始");
        int a =0;
        int b =0;
        //查询分组记录
        HTempContract hTempContract = new HTempContract();
        List<HTempContract> hTempContracts = contractRecordMapper.selectHTempContractListGroup(hTempContract);
        System.out.println("总数为:"+hTempContracts.size());
        for (HTempContract tempContract : hTempContracts) {
            HTempContract hTempContract1 = new HTempContract();
            hTempContract1.setDealerName(tempContract.getDealerName());
            hTempContract1.setSector(tempContract.getSector());
            hTempContract1.setLimitType(tempContract.getLimitType());
            hTempContract1.setExpiryDate(tempContract.getExpiryDate());
            List<HTempContract> hTempContracts1 = contractRecordMapper.selectHTempContractList(hTempContract1);
            System.out.println("查询的数量为:"+hTempContracts1.size());
            TreeSet<String> urlList = new TreeSet<>();
            for (HTempContract contract : hTempContracts1) {
                urlList.add(contract.getFileUrl());
            }
            System.out.println("查询结果："+urlList.size());
            System.out.println("查询结果："+urlList);
            if(urlList.size()>1){
                List<File> files = new ArrayList();
                for (String s : urlList) {
                    String newFileName = s.substring(21, s.length());
                    String filePath = "D:\\ruoyi\\BBB"+  newFileName;
                    File newfile = new File(filePath);
                    files.add(newfile);
                }
                String uuid1 = IdUtils.get16UUID();
                String dizhi ="D:\\ruoyi\\OfflineContract\\"+ "/"+uuid1+".pdf";
                File newfile = new File(dizhi);
                File fileParent = newfile.getParentFile();
                System.out.println(fileParent);
                File f = AsposeUtil.MulFileToOne(files, dizhi);
                a++;
                System.out.println("合并成功");
                for (HTempContract contract : hTempContracts1) {
                    contract.setNewFileUrl("/profile/upload/OfflineContract"+dizhi);
                    contractRecordMapper.updateHTempContract(contract);
                }
                //更新地址
                
                //合并
            }else if (urlList.size() == 1){
                for (String s : urlList) {
                    String newFileName = s.substring(21, s.length());

                    String filePath = "D:\\ruoyi\\BBB"+  newFileName;
                    String uuid = IdUtils.get16UUID();
                    String dizhi ="D:\\ruoyi\\OfflineContract\\"+ "/"+uuid+".pdf";
                    if(filePath.contains("BBBl")){
                        filePath = filePath.replace("BBBl", "BBB");
                    }
                    copy1(filePath.length(),filePath,dizhi);
                    System.out.println("复制成功");
                    //更新
                    for (HTempContract contract : hTempContracts1) {
                        contract.setNewFileUrl("/profile/upload/OfflineContract"+"/"+uuid+".pdf");
                        contractRecordMapper.updateHTempContract(contract);
                    }
                }
            }else{
                System.out.println("空空");
            }

        }
        //根据分组记录查询每条记录
        //创建数组将所有路径pdf进行去重合并
        //将合并后的路径存放数据库，以及本地
        //将数据库更新,将本地目录上传服务器
    }

    @Autowired
    private DealerInformationMapper dealerInformationMapper;

    @Autowired
    private HAmlMapper amlMapper;
    @GetMapping("/report")
    public void report(@RequestBody Map<String, Object> map) throws Exception {
        System.out.println("开始");
        DealerInformation dealerInformation = new DealerInformation();
        ArrayList<String> stringArrayList = new ArrayList<>();
        List<DealerInformation> dealerInformations = dealerInformationMapper.selectDealerInformationList(dealerInformation);
        for (DealerInformation information : dealerInformations) {
            StringBuffer names = new StringBuffer();
            if(information.getDealerName()!=null){
                names.append(information.getDealerName()).append(",");
            }
            if(StringUtils.isNotEmpty(information.getLegalRepresentativeCN())){
                names.append(information.getLegalRepresentativeCN()).append(",");
            }
            if(StringUtils.isNotEmpty(information.getShareholderStructure())){
                String shareholderStructure = information.getShareholderStructure();
                String[] split = shareholderStructure.split(";");
                for(String sp: split){
                    Map<String, Object> objectObjectHashMap = new HashMap<>();
                    ArrayList<String> objects = new ArrayList<>();
                    StringTokenizer stringTokenizer = new StringTokenizer(sp, "#:");
                    while(stringTokenizer.hasMoreElements()){
                        objects.add(stringTokenizer.nextToken());
                    }
                    if(objects.size()==3) {
                        names.append(objects.get(1)).append(",");
                    }
                }
            }
            if(StringUtils.isNotEmpty(information.getIndividualGuarantorCn())){
                String[] strings = information.getIndividualGuarantorCn().split("#");
                for (String string : strings) {
                    names.append(string).append(",");
                }
            }
            if(StringUtils.isNotEmpty(information.getCorporateGuarantorCn())){
                String[] strings = information.getCorporateGuarantorCn().split("#");
                for (String string : strings) {
                    names.append(string).append(",");
                }
            }
            if (names.length()>0) {
                names.deleteCharAt(names.length() - 1);
                System.out.println(names);
                String[] split = names.toString().split(",");
                for (String s : split) {
                    String amlName = amlMapper.getAmlName(s);
                    if(StringUtils.isNotEmpty(amlName)){
                        System.out.println("存在黑名单"+information.getDealerName()+"名单："+s);
                        stringArrayList.add(information.getDealerName()+s+"||");
                    }else{

                    }
                }
            }

        }
        System.out.println("结束"+stringArrayList);

    }


    @GetMapping("/changPdf2")
    public void changPdf2(@RequestBody Map<String, Object> map) throws Exception {
        System.out.println("开始");
        int a =0;
        int b =0;
        //查询分组记录
        HTempContract hTempContract = new HTempContract();
        List<HTempContract> hTempContracts = contractRecordMapper.selectHTempContractListGroup(hTempContract);
        System.out.println("总数为:"+hTempContracts.size());
        for (HTempContract tempContract : hTempContracts) {
            //拿到文件夹
            String fileUrl = tempContract.getFileUrl();
            String newFileName = fileUrl.substring(87, fileUrl.length());
            String filePath = "D:\\ruoyi\\DDD\\"+  newFileName;
            String dizhi = getFileList222(filePath);
            System.out.println(dizhi);
            if(StringUtils.isEmpty(dizhi)){
                throw  new BaseException("空的");
            }
            HTempContract hTempContract1 = new HTempContract();
            hTempContract1.setDealerName(tempContract.getDealerName());
            hTempContract1.setSector(tempContract.getSector());
            hTempContract1.setLimitType(tempContract.getLimitType());
            hTempContract1.setExpiryDate(tempContract.getExpiryDate());
            List<HTempContract> hTempContracts1 = contractRecordMapper.selectHTempContractList(hTempContract1);
            System.out.println("查询的数量为:"+hTempContracts1.size());
            for (HTempContract contract : hTempContracts1) {
                contract.setNewFileUrl(dizhi);
                contractRecordMapper.updateHTempContract(contract);
            }

        }
        //根据分组记录查询每条记录
        //创建数组将所有路径pdf进行去重合并
        //将合并后的路径存放数据库，以及本地
        //将数据库更新,将本地目录上传服务器
    }

    public  void copy1(int oldLength,String oldPath, String newPath) throws IOException {
        File f1 = new File(oldPath);
        File f2 = new File(newPath+oldPath.substring(oldLength));

        //如果f1为空 直接退出
        if (!f1.exists()){
            System.out.println(oldPath);
            System.out.println("1234");
            return;

        }


        if (f1.isDirectory()) {
            //目标目录不存在此文件夹就进行新建
            if (!f2.exists())
                f2.mkdirs();

            File[] f1s = f1.listFiles();
            if (f1s != null) {
                for (File file : f1s) {
                    copy1(oldLength, file.getPath(), newPath);
                }
            }
        } else {
            //如果是文件的话就进行复制
            f2.delete();    //如果存在存量数据就先删除
            Files.copy(f1.toPath(), f2.toPath());
        }
    }



    public  String getFileList222(String path) {
        List<File> rsList = new ArrayList<>();
        if (path == null || path.equals("")) {
            System.out.println("Error: path is blank.");
            return "";
        }
        File file = new File(path);
        if (!file.exists()) {
            System.out.println("Error: path is not existed.");
            return "";
        }
        // 处理文件
        if (file.isFile()) {
            System.out.println("Info: Only has a file.");
            rsList.add(file);
            return "";
        }
        // 处理文件夹
        if (null == file.listFiles()) {
            System.out.println("Info: Only has a empty directory.");
            rsList.add(file);
            return "";
        }
        LinkedList<File> forDealList = new LinkedList<>();
        forDealList.addAll(Arrays.asList(file.listFiles()));
        int m = 1;
        while (!forDealList.isEmpty()) {
            File firstFile = forDealList.removeFirst();
            if (firstFile.isFile()) {
                rsList.add(firstFile);
            }
        }
        String uuid ="";
        if(rsList.size()==1){
            try {
                System.out.println("无需合并");
                uuid = IdUtils.get16UUID();
                String newPath ="D:\\ruoyi\\OfflineContractByPeugeot\\"+ "/"+uuid+".pdf";
                copy1(rsList.get(0).getPath().length(),rsList.get(0).getPath(),newPath);
            }catch (Exception e){
                e.printStackTrace();
            }
        }else if(rsList.size()>1){
            try {
                uuid = IdUtils.get16UUID();
                String dizhi ="D:\\ruoyi\\OfflineContractByPeugeot\\"+ "/"+uuid+".pdf";
                File f = AsposeUtil.MulFileToOne(rsList, dizhi);

            }catch (Exception e){
                System.out.println("异常+"+path);
                e.printStackTrace();
            }
        }else{
            System.out.println("没有文件");
        }
        System.out.println("结束");
        return "/profile/upload/OfflineContract"+"/"+uuid+".pdf";
    }

}
